﻿using NFine.Application._02_Weixin;
using NFine.Code;
using NFine.Domain._02_ViewModel;
using NFine.Domain._03_Entity.Weixin;
using NFine.Web.App_Start;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WeiXin.SDK.Helpers;
using WeiXin.SDK.Pay;

namespace NFine.Web.Areas.WeiXinAreas.Controllers
{
    public class CompanysController : Controller
    {
        private Log logger = LogFactory.GetLogger("LiveController");
        private CompanyApp app = new CompanyApp();
        private Company_FileApp fileApp = new Company_FileApp();
        private Company_FileTypeApp typeApp = new Company_FileTypeApp();
        private Companys_userApp userApp = new Companys_userApp();
        private TradingRecordApp tradapp = new TradingRecordApp();
        //
        // GET: /WeiXinAreas/Companys/
        public ActionResult WaitJoin()
        {
            return View();
        }
        public ActionResult WaitAudit()
        {
            return View();
        }
        public ActionResult Index(string searchInput = "")
        {
           if (Session["user"] != null)
            {
                var model = Session["user"] as UserInfoModel;
                //查询是否已经申请过
                CompanyEntity entity = app.getEntityByUserId(model.USERID);
                if (entity == null)
                {
                    return Redirect("WaitJoin");
                }
                else
                {
                    if (entity.State == 1)
                    {
                        //获取已经审核通过的公司
                        var list = app.getList(1, searchInput);
                        ViewData["search"] = searchInput;
                        return View(list);
                    }else
                    {
                        return Redirect("WaitAudit");
                    }
                }
            }
            else
            {
                return Redirect("/Weixin/NeedToCompanys?uri=/WeiXinAreas/Companys/Index");
            }

            ////获取已经审核通过的公司
            //var list =  app.getList(1, searchInput);
            //ViewData["search"] = searchInput;
            //return View(list);
        }
        public ActionResult Join()
        {
            //CompanyEntity entity = new CompanyEntity();
            //ViewData["state"] = -1;//未申请
            //return View(entity);
            if (Session["user"] != null)
            {
                var model = Session["user"] as UserInfoModel;
                //查询是否已经申请过
                CompanyEntity entity = app.getEntityByUserId(model.USERID);
                if (entity != null)
                {
                    if (entity.State != 1)//未审核
                        return Redirect("WaitAudit");
                    else
                        return Redirect("Index");
                }
                else
                {
                    entity = new CompanyEntity();
                    ViewData["state"] = -1;//未申请
                }
                return View(entity);
            }
            else
            {
                return Redirect("/Weixin/NeedToCompanys?uri=/WeiXinAreas/Companys/Join");
            }
        }
      
       [HttpPost]
        public JsonResult uploadLogo()//
        {
            try
            {
                 HttpPostedFileBase logo=Request.Files["uploaderInput"];
              
                    var fileExt = System.IO.Path.GetExtension(logo.FileName).Substring(1);
                    Random r = new Random();
                    var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + "." + fileExt;
                    // 文件上传后的临时保存路径
                    if (!System.IO.Directory.Exists(Server.MapPath("~/UploadFiles/temp/")))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath("~/UploadFiles/temp/"));
                    }
                    //保存原图片
                var filepath = System.IO.Path.Combine(Server.MapPath("~/UploadFiles/temp"), filename);
                logo.SaveAs(filepath);
             
                //生成缩略图
                var filename_s = "_"+filename;
                Image _image = System.Drawing.Image.FromStream(logo.InputStream);
                cutAvatar(filepath, 0, 0, _image.Width, _image.Height, 75L, Server.MapPath("~/UploadFiles/temp"), filename_s, 100);
                //删除原图片
                System.IO.File.Delete(Server.MapPath("~/UploadFiles/temp/"+ filename));

                return Json(new { msg = filename_s });
            }
            catch
            {
                return Json(new { msg = 0 });
            }
        }
        [HttpPost]
        public JsonResult submit(CompanyEntity entity)
        {
            if (Session["user"] != null)
            {
               var model=  Session["user"] as UserInfoModel;
                entity.UserId = model.USERID;

                entity.JoinDate = DateTime.Now;

                if (!string.IsNullOrEmpty(entity.Logo))
                {
                    //保存公司logo
                    string newPath = Request.MapPath("~/UploadFiles/Logo/");

                    FileInfo file = null;
                    if (!Directory.Exists(newPath))
                    {
                        Directory.CreateDirectory(newPath);
                    }
                    file = new FileInfo(Request.MapPath("~/UploadFiles/temp/" + entity.Logo));

                    file.MoveTo(newPath + entity.Logo);
                    entity.Logo = "/UploadFiles/Logo/" + entity.Logo;
                }

                var result = app.insert(entity);
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取更多公司
        /// </summary>
        /// <param name="searchInput"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public ContentResult getMore(string searchInput = "", int start = 0)
        {
            var list = app.getList(1, searchInput, start );
            return Content(list.ToJson());
        }

        #region 创建缩略图
        /// <summary>
        /// 创建缩略图
        /// </summary>
        public void cutAvatar(string imgSrc, int x, int y, int width, int height, long Quality, string path, string filename, int t)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string SavePath = Path.Combine(path, filename);

            Image original = Image.FromFile(imgSrc);

            Bitmap img = new Bitmap(t, t, PixelFormat.Format24bppRgb);

            img.MakeTransparent(img.GetPixel(0, 0));
            img.SetResolution(72, 72);
            using (Graphics gr = Graphics.FromImage(img))
            {
                if (original.RawFormat.Equals(ImageFormat.Jpeg) || original.RawFormat.Equals(ImageFormat.Png) || original.RawFormat.Equals(ImageFormat.Bmp))
                {
                    gr.Clear(Color.Transparent);
                }
                if (original.RawFormat.Equals(ImageFormat.Gif))
                {
                    gr.Clear(Color.White);
                }


                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gr.SmoothingMode = SmoothingMode.AntiAlias;
                gr.CompositingQuality = CompositingQuality.HighQuality;
                gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                using (var attribute = new System.Drawing.Imaging.ImageAttributes())
                {
                    attribute.SetWrapMode(WrapMode.TileFlipXY);
                    gr.DrawImage(original, new Rectangle(0, 0, t, t), x, y, width, height, GraphicsUnit.Pixel, attribute);
                }
            }
            ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
            if (original.RawFormat.Equals(ImageFormat.Jpeg))
            {
                myImageCodecInfo = GetEncoderInfo("image/jpeg");
            }
            else
                if (original.RawFormat.Equals(ImageFormat.Png))
            {
                myImageCodecInfo = GetEncoderInfo("image/png");
            }
            else
                    if (original.RawFormat.Equals(ImageFormat.Gif))
            {
                myImageCodecInfo = GetEncoderInfo("image/gif");
            }
            else
                        if (original.RawFormat.Equals(ImageFormat.Bmp))
            {
                myImageCodecInfo = GetEncoderInfo("image/bmp");
            }

            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, Quality);
            myEncoderParameters.Param[0] = myEncoderParameter;
            img.Save(SavePath, myImageCodecInfo, myEncoderParameters);
            original.Dispose();
        }

        //根据长宽自适应 按原图比例缩放 
        private static Size GetThumbnailSize(System.Drawing.Image original, int desiredWidth, int desiredHeight)
        {
            var widthScale = (double)desiredWidth / original.Width;
            var heightScale = (double)desiredHeight / original.Height;
            var scale = widthScale < heightScale ? widthScale : heightScale;
            return new Size
            {
                Width = (int)(scale * original.Width),
                Height = (int)(scale * original.Height)
            };
        }
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
        #endregion
        /// <summary>
        /// 文件列表
        /// </summary>
        /// <param name="searchInput"></param>
        /// <returns></returns>
        public ActionResult FileIndex(string searchInput = "", int cateId =0, int indexId = 0)
        {
             if (Session["user"] != null)
             {
                 var model = Session["user"] as UserInfoModel;
                  Companys_usersEntity user = userApp.GetUserInfoByUniond(model.WECHATACCOUNT);
                 ViewData["isPay"] = user.ISPAY;

                 //获取文件分类
                 var typeList = typeApp.getList();
                // 获取所有文件
                 var list = fileApp.getAllList(cateId, searchInput, 0,user.USERID,user.ISPAY);
                 ViewData["cateList"] = typeList;
                 ViewData["liveList"] = list;
                 ViewData["cateId"] = cateId;
                 ViewData["indexId"] = indexId;
                 ViewData["search"] = searchInput;

                //获取开通会员金额
                ViewData["PayMoney"] = app.getOpenAmount();

                 return View(list);
             }
             else
             {
                 return Redirect("/Weixin/NeedToCompanys?uri=/WeiXinAreas/Companys/FileIndex");
             }
            /* //获取文件分类
             var typeList = typeApp.getList();
            // 获取所有文件
             var list = fileApp.getAllList(cateId, searchInput, 0,23,0);
             ViewData["cateList"] = typeList;
             ViewData["liveList"] = list;
             ViewData["cateId"] = cateId;
             ViewData["indexId"] = indexId;
             ViewData["search"] = searchInput;


             ViewData["isPay"] = 0;
            // 获取开通会员金额
             ViewData["PayMoney"] = app.getOpenAmount();
             return View(list);*/
        }
        /// <summary>
        /// 获取更多文件
        /// </summary>
        /// <param name="cateId"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public ContentResult getMoreFile(int cateId, int start, string searchInput)
        {
            var model = Session["user"] as UserInfoModel;
            Companys_usersEntity user = userApp.GetUserInfoByUniond(model.WECHATACCOUNT);
            //获取文件
            var list = fileApp.getAllList(cateId, searchInput, start * 10,user.USERID,user.ISPAY);
                return Content(list.ToJson());
            
        }
        /// <summary>
        /// 付款
        /// </summary>
        /// <returns></returns>
        public string pay(int FileId,decimal money)
        {
            if (Session["user"] != null )
            {
                var model = Session["user"] as UserInfoModel;
               
                //交易记录
                TradingRecordEntity entity_trad = new TradingRecordEntity();
                entity_trad.RID = Common.CreateNo();
                entity_trad.PAYMONEY = money;// Convert.ToDecimal(WeixinConfig.PayMoney);
                entity_trad.PAYEDUSERID= model.USERID;
                entity_trad.INPUTTIME = DateTime.Now;
                entity_trad.PAYSTATUS = 0;
                entity_trad.PREPAIDORDER = "";
                entity_trad.CALLBACKSTATUS = 0;
                entity_trad.FileId = FileId;

                //配置文件中设置支付金额
                int total_fee = (int)(money * 100);

                dynamic d = WxPayAPI.UnifiedOrder(WeixinConfig.AppID, WeixinConfig.mch_id, "WEB", entity_trad.RID,
                "付费查看", "付费查看", entity_trad.RID, entity_trad.RID, "CNY", total_fee, GetClientIp(),
                DateTime.Now.ToString("yyyyMMddHHmmss"), DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"), "",
                WeixinConfig.Domain + "/WeiXinAreas/Companys/ReceiveInfo", "JSAPI", "", model.openid, WeixinConfig.PartnerKey);

                if (d.return_code != null && d.return_code.Value == "SUCCESS")
                {
                    entity_trad.PREPAIDORDER = d.prepay_id.Value;
                    if (tradapp.Insert(entity_trad))
                    {
                        var stringADict = new Dictionary<string, string>();
                        stringADict.Add("appId", WeixinConfig.AppID);
                        stringADict.Add("nonceStr", Util.CreateNonce_str());
                        stringADict.Add("signType", "MD5");
                        stringADict.Add("package", "prepay_id=" + d.prepay_id.Value);
                        stringADict.Add("timeStamp", Util.CreateTimestamp().ToString());

                        string sign = WxPayAPI.Sign(stringADict, WeixinConfig.PartnerKey);
                        StringBuilder sb = new StringBuilder("{");
                        sb.Append("\"state\":\"SUCCESS\",\"wx\":");
                        sb.Append("{\"appId\":\"" + stringADict["appId"] + "\",");
                        sb.Append("\"timeStamp\":\"" + stringADict["timeStamp"] + "\",");
                        sb.Append("\"nonceStr\":\"" + stringADict["nonceStr"] + "\",");
                        sb.Append("\"package\":\"" + stringADict["package"] + "\",");
                        sb.Append("\"signType\":\"" + stringADict["signType"] + "\",");
                        sb.Append("\"paySign\":\"" + sign + "\"}");
                        // sb.Append("\"playurls\":[" + urls.Remove(0, 1) + "]");
                        sb.Append("}");
                        return sb.ToString();
                    }
                }
                else
                {
                    return "生成预支付订单失败：" + ((DynamicXml)d).getEle(0).ToString() + "    " + GetClientIp();
                }
            }
            return "no session";
        }
        public void ReceiveInfo()
        {
            string resultFromWx = getPostStr();
            logger.Debug("支付回调：" + resultFromWx);
            dynamic res = new DynamicXml(resultFromWx);
            TradingRecordEntity entity_trad = tradapp.getTradingRecord(res.attach.Value);
            if (entity_trad != null && entity_trad.CALLBACKSTATUS == 0)
            {
                entity_trad.CALLBACKSTATUS = 1;
                entity_trad.PAYSTATUS = 1;
                tradapp.update(entity_trad);
                if (entity_trad.FileId == 0)
                {
                    Companys_usersEntity user = userApp.GetUserInfo(entity_trad.PAYEDUSERID);
                    user.ISPAY = 1;
                    userApp.update(user);
                }
            }
        }
        public string getPostStr()
        {
            Int32 intLen = Convert.ToInt32(Request.InputStream.Length);
            byte[] b = new byte[intLen];
            Request.InputStream.Read(b, 0, intLen);
            return System.Text.Encoding.UTF8.GetString(b);
        }
        /// <summary>
        /// 获取客户端Ip
        /// </summary>
        /// <returns></returns>
        private String GetClientIp()
        {
            String clientIP = "";
            if (System.Web.HttpContext.Current != null)
            {
                clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(clientIP) || (clientIP.ToLower() == "unknown"))
                {
                    clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];
                    if (string.IsNullOrEmpty(clientIP))
                    {
                        clientIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                }
                else
                {
                    clientIP = clientIP.Split(',')[0];
                }
            }
            return clientIP;
        }
        #region 截取图片保存
        /* [HttpPost]
         public JsonResult upload_cut(string base64Img)
         {
             if (!System.IO.Directory.Exists(Server.MapPath("~/UploadFiles/temp/")))
             {
                 System.IO.Directory.CreateDirectory(Server.MapPath("~/UploadFiles/temp/"));
             }
             var bitmap = Base64StringToImage(base64Img);
             bitmap.Save(Server.MapPath("~/UploadFiles/temp/1.jpg"), ImageFormat.Jpeg);
             return Json(1);
         }
         public static Bitmap Base64StringToImage(string base64Img)
         {
             byte[] bytes = Convert.FromBase64String(base64Img.Replace("data:image/jpeg;base64,", "").Replace("%2B", "+"));
             MemoryStream ms = new MemoryStream();
             ms.Write(bytes, 0, bytes.Length);
             Bitmap bmp = new Bitmap(ms);

             return bmp;
         }*/
        #endregion
    }
}
